package com.wendal.java.happydog.bean;

import java.lang.reflect.Field;
import java.util.HashSet;
import java.util.Set;

import net.sf.json.JSONObject;

import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public abstract class AbstractBean {
	
	protected JSONObject jsonObject;
	
	private Log log = LogFactory.getLog(getClass());
	
	public AbstractBean(JSONObject jsonObject){
		this.jsonObject = jsonObject;
		initBean();
	}
	
	protected Set<String> getIgnoreField(){
		Set<String> ignoreField = new HashSet<String>();
		ignoreField.add("jsonObject");
		ignoreField.add("log");
		return ignoreField;
	}
	
	protected void initBean(){
		Field field;
		Set<String> ignoreField = getIgnoreField();
		Class<? extends AbstractBean> cc = getClass();
		for (Object info_name : jsonObject.names()) {
			if(info_name == null || info_name.toString().trim().isEmpty()) continue;
			
			String field_name = String.valueOf(info_name);
			if(ignoreField.contains(field_name))  continue;
			
			try {
				field = cc.getDeclaredField(field_name);
//				if(Modifier.isPrivate(field.getModifiers())){
				field.set(this, jsonObject.getString(field_name));
//				}
			} catch (SecurityException e) {
				log.debug("无法填入一个Field", e);
			} catch (NoSuchFieldException e) {
				log.debug("该JSon中包含未知的字段="+info_name);
			}catch (IllegalArgumentException e) {
				log.debug("无法填入一个Field", e);
			} catch (IllegalAccessException e) {
				log.debug("无法填入一个Field", e);
			}
		}
	}
	
	@Override
	public String toString() {
		return ToStringBuilder.reflectionToString(this);
	}
}
